package org.anq.ddm.controller;

import com.alibaba.fastjson.JSONObject;
import org.anq.ddm.pojo.FormValue;
import org.anq.ddm.pojo.Instance;
import org.anq.ddm.pojo.Task;
import org.anq.ddm.service.BpmnProcessService;
import org.anq.ddm.service.CamundaService;
import org.anq.ddm.service.FormService;
import org.anq.ddm.service.InstanceService;
import org.anq.ddm.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/instance")
public class InstanceController {

    @Autowired
    FormService formService;

    @Autowired
    CamundaService camundaService;

    @Autowired
    InstanceService instanceService;

    @Autowired
    BpmnProcessService bmnProcessService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 准备创建流程，该部分为获取流程的初始表单，让用户填写，当用户提交后，调用startInstance。
     *
     * @return
     */
    @RequestMapping(value = "/preStartInstanceForm/{definationKey}", method = RequestMethod.GET)
    public ApiResult preStartInstance(@PathVariable String definationKey) {
        Map<String,Object> map = new HashMap<>();
        ApiResult result = new ApiResult();

        String formname = this.camundaService.getStartFormKey(definationKey);
        if (formname != null) {
            map.put("formId",formname);
            map.put("formUi",this.formService.findByFromKey(formname).getFormvalue());
            result.setData(map);
            return result;
        } else {
            return result;
        }
    }

    /**
     * 准备创建流程，该部分为获取流程的初始表单，让用户填写，当用户提交后，调用startInstance。
     *
     * @return
     */
    @RequestMapping(value = "/startInstance/{definationKey}/{formId}", method = RequestMethod.POST)
    public ApiResult startInstance(@PathVariable String definationKey, @PathVariable String formId, @RequestBody Map<String,Object> values) {
        ApiResult result = new ApiResult();
        String instanceId = this.camundaService.startInstance(definationKey,values);

        Instance a = new Instance();
        a.setProcessid(this.bmnProcessService.findByProcessKey(definationKey).getId());
        a.setInstanceid(instanceId);
        a.setCreatetime("test-time");
        a.setStatus(1);
        a.setUid("test-user");
        this.instanceService.save(a);

        String taskId = this.camundaService.queryTaskIdByInstanceId(instanceId).get(0);

        this.camundaService.completeInstance(instanceId, "test", null, values);


        //存入mongodb
        FormValue mv = new FormValue();
        mv.setTaskid(taskId);
        mv.setId(UUID.randomUUID().toString());
        mv.setInstanceid(instanceId);
        mv.setFormid(formId);
        mv.setContent(values);
        mv.setCreatetime("test-time");
        mv.setUser("test-user");
        mongoTemplate.save(mv);
        result.setMessage("申请成功");
        return result;
    }

    /**
     * 完成当前任务，需要考虑多人共同完成一个任务的情况。最好是传递taskId，然后用try catch包围一下。
     * @return
     */
    @RequestMapping(value = "/completeTask/{instanceId}/{formId}/{taskId}", method = RequestMethod.POST)
    public ApiResult completeTask(@PathVariable String instanceId,@PathVariable String formId,@PathVariable String taskId,@RequestBody Map<String,Object> values){
        Map<String,Object> param = values;
        ApiResult result = new ApiResult();
        //存入mongodb
        FormValue mv = new FormValue();
        mv.setTaskid(taskId);
        mv.setId(UUID.randomUUID().toString());
        mv.setInstanceid(instanceId);
        mv.setFormid(formId);
        mv.setContent(values);
        mv.setCreatetime("test-time");
        mv.setUser("test-user");
        mongoTemplate.save(mv);
        this.camundaService.completeInstance(instanceId, "test", null, param);
        result.setMessage("完成当前任务");
        return result;
    }

    /**
     * 展示申请列表
     * @return
     */
    @RequestMapping(value = "/instances/{definationKey}", method = RequestMethod.GET)
    public ApiResult listAllInstance(@PathVariable String definationKey){
        ApiResult result = new ApiResult();
        List<Task> taskList = this.camundaService.queryAllTask(definationKey);
        List<Instance> applyList = new ArrayList<>();

        if(taskList!=null){
            for(Task t:taskList){
                applyList.add(this.instanceService.getApplyByInstanceId(t.getInstanceId()));
            }
        }
        result.setData(applyList);
        return result;
    }


    /**
     * 根据设计的列表表单展示申请
     * @param definationKey
     * @return
     */
    @RequestMapping(value = "/instancesDetail/{definationKey}", method = RequestMethod.GET)
    public ApiResult applyListDataM(@PathVariable String definationKey){
        ApiResult result = new ApiResult();
        List<Task> taskList = this.camundaService.queryAllTask(definationKey);
        List<Map<String,Object>> list = new ArrayList<>();
        if(taskList!=null){
            for(Task t:taskList){
                Query q = new Query();
                q.addCriteria(Criteria.where("instanceid").is(t.getInstanceId()));
                List<FormValue> mlist = mongoTemplate.find(q, FormValue.class);
                if(mlist!=null){
                    for(FormValue m:mlist) {
                        Map<String,Object> map = m.getContent();
                        if(map!=null) {
                            map.put("instanceid", m.getInstanceid());
                            map.put("createtime", m.getCreatetime());
                            map.put("formid", m.getFormid());
                            map.put("user", m.getUser());
                            map.put("content",m.getContent());
                            list.add(map);
                        }
                    }
                }
            }
        }
        result.setData(list);
        return result;
    }


}
